package com.yq.ylmall.product.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.yq.ylmall.product.mapper.RegionMapper;
import com.yq.ylmall.vo.product.RegionExcelVo;

import java.util.List;

public class RegionExcelHelper<T> extends AnalysisEventListener<T> {
    /**
     * 每隔100条存储数据库，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    //获取mapper对象
    private final RegionMapper regionMapper;
    public RegionExcelHelper(RegionMapper regionMapper){
        this.regionMapper = regionMapper;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        RegionExcelVo data = (RegionExcelVo) t;
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // excel解析完毕以后需要执行的代码
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
    }
    private void saveData() {
        regionMapper.batchInsert(cachedDataList);
    }
}